162. 寻找峰值
为保证权益,题目请参考 162. 寻找峰值(From LeetCode).
解决方案1
CPP
C++
//
// Created by lenovo on 2020-09-18.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 顺序法
//class Solution {
//public:
// int findPeakElement(vector<int> &nums) {
// for(int i=0;i<nums.size()-1;i++){
// if(nums[i] > nums[i+1]){
// return i;
// }
// }
// return nums.size()-1;
// }
//};
class Solution {
private:
int helper(vector<int> &nums, int l, int r) {
if (l == r) {
return l;
}
int m = (l + r) / 2;
if (nums[m] > nums[m + 1]) {
return helper(nums, l, m);
} else {
return helper(nums, m+1, r);
}
}
public:
// TODO: Binary Finder
int findPeakElement(vector<int> &nums) {
return this->helper(nums, 0, nums.size() - 1);
}
};
void runTest(){
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(1);
Solution so;
cout << so.findPeakElement(vec) << endl;
}
int main() {
runTest();
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Python
python
# 162. 寻找峰值
# https://leetcode-cn.com/problems/find-peak-element/
################################################################################
from typing import List
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
if len(nums) == 1:
return 0
if nums[0] > nums[1]:
return 0
if nums[len(nums) - 1] > nums[len(nums) - 2]:
return len(nums) - 1
l = 1
r = len(nums) - 2
while l <= r:
m = (l + r) // 2
if nums[m] < nums[m + 1]:
l = m + 1
else:
if nums[m] < nums[m - 1]:
r = m - 1
else:
return m
################################################################################
if __name__ == "__main__":
solution = Solution()
print(solution.findPeakElement([2, 3, 1]))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39